package com.wuyixu.utils;

import java.util.Calendar;
import java.util.Date;


public class DateUtil {
	/**
	 * 
	 * 功能:根据传入的日期返回日期的月初。如:传入 2020-04-24 ，返回 2020-04-01 00:00:00
	 *
	 * @param date
	 * @return
	 */
	public static Date getInitMonth(Date date){
		Calendar c = Calendar.getInstance();
		//用传入的日期初始化日历类
		c.setTime(date);
		//设置这个月的月初即:改变这个月的日期位第一天
		c.set(Calendar.DAY_OF_MONTH, 1);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		return c.getTime();
		
	}
	/**
	 * 
	 * 功能:根据传入的日期返回日期的月初。如: 2020-04-24  ，返回 2020-04-30 23:59:59
	 *
	 * @param date
	 * @return
	 */
	public static Date getEndMonth(Date date){
		Calendar c = Calendar.getInstance();
		//用传入的日期初始化日历类
		c.setTime(date);
		//让月加1 2020-05-24 再变成月初 2020-05-01 再减去一秒
		c.add(Calendar.MONTH,1);
		Date nextMonthInit = getInitMonth(c.getTime());
		//初始化日历类
		c.setTime(nextMonthInit);
		c.add(Calendar.SECOND,-1);
		return c.getTime();
		
	}
	/**
	 * 
	 * 功能:随机产生一个min 和max之间的日期
	 *
	 * @param min
	 * @param max
	 * @return
	 */
	public static Date random(Date min,Date max){
		long t1 = min.getTime();
		long t2 = max.getTime();
		long t = (long)(Math.random()*(t2-t1)+t1);
		return new Date(t);
	}
	/**
	 * 
	 * 功能:根据日期计算年龄
	 *
	 * @param birthday
	 * @return
	 */
	public static int getAgeBybirthday(Date birthday){
		//获取系统当前年 月 日
		Calendar c = Calendar.getInstance();
		int nowYear = c.get(Calendar.YEAR);
		int nowMonth = c.get(Calendar.MONTH);
		int nowDay = c.get(Calendar.DAY_OF_MONTH);
		//获取传入日期的生日的年 月日
		Calendar c2 = Calendar.getInstance();
		c2.setTime(birthday);
		int birthdayYear = c2.get(Calendar.YEAR);
		int birthdayMonth = c2.get(Calendar.MONTH);
		int birthdayDay = c2.get(Calendar.DAY_OF_MONTH);
		if(nowYear <birthdayYear){
			throw new RuntimeException("传入的日期错误");
		}
		int age = nowYear -birthdayYear;
		if(nowMonth<birthdayMonth){
			age --;
		}
		if(nowMonth==birthdayMonth && nowDay<birthdayDay){
			age--;
		}
		return age;
	}
}
